import CryptoJS from 'crypto-js';
// 正式
//var baseURL1 = 'https://api.hnhr66.cn/';
//var baseURL2 = 'https://admins-api.hnhr66.cn/';


// 正式测试
//var baseURL1 = 'http://apitest.hnhr66.cn/';


if (process.env.NODE_ENV === 'development') {
	var baseURL1 = 'http://121.89.195.116:9882/';
} else {

	var baseURL1 = 'https://rh.wexiang.vip:11243/server/';
}


var baseURL2 = 'https://very2.wexiang.vip/';



function generateHmacSha1(message, secretKey) {
	return CryptoJS.HmacSHA1(message, secretKey).toString(CryptoJS.enc.Hex);
}


var getSignature = () => {
	let user = uni.getStorageSync('user')
	var url
	if (process.env.NODE_ENV === 'development') {
		url =
			`${uni.getStorageSync('thaturl').fuwuselect==1?'http':'https'}://${uni.getStorageSync('thaturl').yumingvalue}:${uni.getStorageSync('thaturl').duankovalue}/` +
			'getSignature'
	} else {
		url = 'https://rh.wexiang.vip:11243/server/getSignature'
	}

	return new Promise((resolve, reject) => {
		uni.request({

			//url: `${uni.getStorageSync('thaturl').fuwuselect==1?'http':'https'}://${uni.getStorageSync('thaturl').yumingvalue}:${uni.getStorageSync('thaturl').duankovalue}/` +
			//'getSignature',

			url,
			header: {
				'Authorization': uni.getStorageSync("token") ? uni.getStorageSync("token") : '',
				'APP': new Date().getTime()
			},
			method: 'GET',
			success: (res) => {
				if (res.statusCode == 200) {
					if (res.data.code == 200) {

						let str = user.appKey + res.data.data.msgId + res.data.data.requestTime
						let upperStr = str.toUpperCase()

						res.data.data.signature = generateHmacSha1(upperStr, user.secretKey)

						res.data.data.appCode = user.appCode
						res.data.data.appKey = user.appKey

						resolve(res.data.data)

					}
				} else {
					reject(res)
					if (res.message) {
						uni.showToast({
							title: res.message,
							icon: "none"
						})
					} else {
						uni.showToast({
							title: res.data.message,
							icon: "none"
						})
					}
				}
			}
		})
	})
}

uni.setStorageSync('upimg', baseURL2); //邀请码
import w_md5 from '/js_sdk/zww-md5/w_md5.js'


export function lkrequest(urls, data, method, server, token) {

	let url = ''
	if (process.env.NODE_ENV === 'development') {
		url = `http://${uni.getStorageSync('user').monitorIp}/` + urls

	} else {

		url = 'https://rh.wexiang.vip:11243/monitors/' + urls

	}
	return new Promise((resolve, reject) => {
		getSignature().then(res => {
			// 原始字符串
			let str = "dqyyfbptyg:1234";

			// 使用btoa()进行Base64编码
			let encodedStr = btoa(str);


			uni.request({
				url,
				header: {
					'Authorization': 'Basic ' + encodedStr,
					'Content-Type': 'application/json',
					'X-ServerCode': server,
					'X-MsgId': res.msgId,
					'X-RequestTime': res.requestTime,
					'X-AppCode': res.appCode,
					'X-AppKey': res.appKey,
					'X-Signature': res.signature,
					"X-Token": token,
					"X-StreamUuid": 'zxb123456789019876543255sd',
				},
				method: method ? method : 'GET',
				data: data ? data : {},
				success: (res) => {
					if (res.statusCode == 200) {
						if (res.data.returnCode == '8888') {
							if (res.data.errorCode == "100202999") {
								uni.showToast({
									title: '操作失败，请检查输入信息，并确认设备是否支持该功能',
									icon: "none"
								})
							} else {
								if(res.data.errorCode == "200010035"||res.data.errorCode == "200010002"){
									console.log('失败');
								}else{
									uni.showToast({
										title: res.data.errorMsg,
										icon: "none"
									})
								}
							}
							return reject(res)
						}
						resolve(res.data);
					} else if (res.statusCode == 401) {
						// uni.removeStorageSync('token')
						// uni.showToast({
						// 	title: '登录已过期，请重新登录',
						// 	icon: "none"
						// })
						// uni.reLaunch({
						// 	url: "/pages/index/index"
						// })

						// reject(res)
					} else {
						reject(res)
						if (res.data.result) {
							uni.showToast({
								title: res.data.result,
								icon: "none"
							})
						} else {
							uni.showToast({
								title: res.data.message,
								icon: "none"
							})
						}
					}
				},
				complete() {
					uni.hideLoading()
				},
				fail: (res) => {

					reject(res)
					uni.showToast({
						title: "系统频繁，稍后重试",
						icon: "none"
					})
				}
			})
		})
	})
}

export function lkfetch(urls, data = {}, method = 'GET') {
	let url;
	let turl = uni.getStorageSync('thaturl');

	url = turl.fuwuselect == 1 ? 'http://' : 'https://';

	if (process.env.NODE_ENV === 'development') {
		url += turl.yumingvalue + ':' + turl.duankovalue + urls;
	} else {

		url = 'https://rh.wexiang.vip:11243/server' + urls;
	}


	return new Promise((resolve, reject) => {
		const isFormData = data instanceof FormData;

		fetch(url, {
				method,
				headers: {
					'Authorization': uni.getStorageSync("token") || '',
					'APP': '5152',
					...(isFormData ? {} : {
						'Content-Type': 'application/json'
					}) // 处理 FormData
				},
				body: method === 'GET' ? null : (isFormData ? data : JSON.stringify(data))
			})
			.then(async response => {
				if (!response.ok) {
					const errData = await response.json().catch(() => ({})); // 避免解析失败
					if (response.status === 401) {
						uni.removeStorageSync('token');
						uni.showToast({
							title: '登录已过期，请重新登录',
							icon: "none"
						});
						setTimeout(() => {
							uni.reLaunch({
								url: "/pages/index/index"
							});
						}, 500);
					} else {
						uni.showToast({
							title: errData.msg || errData.message || "请求失败",
							icon: "none"
						});
					}
					reject(errData);
					return;
				}
				// 处理 204 No Content 情况
				const responseData = response.status === 204 ? {} : await response.json();
				resolve(responseData);
			})
			.catch(error => {
				console.error("请求失败", error);
				uni.showToast({
					title: "系统繁忙，稍后重试",
					icon: "none"
				});
				reject(error);
			});
	});
};